<?php
/**
 * alltosun.com 对外接口控制器 index.php
 * ============================================================================
 * 版权所有 (C) 2009-2014 北京互动阳光科技有限公司，并保留所有权利。
 * 网站地址:   http://www.alltosun.com
 * ----------------------------------------------------------------------------
 * 许可声明：这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
 * ============================================================================
 * $Author: 张元昊 (zhangyh@alltosun.com) $
 * $Date: 2014-11-17 上午11:30:26 $
 * $Id$
*/
class Action
{

    public $appkey;
    public $appskey;
    public $randid;
    public $config; //基本的配置信息
    public $key;
    public $return_msg;

    public function __construct(){
            $this->appkey     = Request::Post('appkey', '');
            $this->randid     = Request::Post('randid', '');
            $this->key        = Request::Post('key', '');
            $this->config     = auth_config::$auth_api[$this->appkey];
            $this->appskey    = $this->config['skey'];
            $this->return_msg = auth_config::$auth_return_msg;
    }

    public function __call($action = "", $param = array()) {
        $m = Request::Post('m', '');
        $c = Request::Post('c', '');
        $key = $this->key;
        if($m == '' || $c == '' || $key == '') {
            auth_helper::returnAuthData($this->return_msg['parm_err'], __LINE__);
        }
        if(!array_key_exists($m, auth_config::$auth_m)) {
            auth_helper::returnAuthData($this->return_msg['mod_err'], __LINE__);
        }
        $this->$c();
    }

    public function register()
    {
        if(!auth_helper::checkGen($this->randid, $this->appkey, $this->appskey, $this->key))
        {
            auth_helper::returnAuthData(auth_config::$auth_return_msg['check_err'],__LINE__);
        }

        $email    = trim(Request::Post('email', ''));
        $mobile   = trim(Request::Post('mobile', ''));
        $password = trim(Request::Post('password', ''));
        $smscode  = trim(Request::Post('smscode', ''));
        //$imgcode  = trim(Request::Post('imgcode', ''));
        $nickname = trim(Request::Post('nickname', ''));

        // $unickname = $nickname.'@'.mt_rand(1000, 100000);

        if(empty($email) && empty($mobile)) {
            auth_helper::returnAuthData(auth_config::$auth_return_msg['parm_err'], __LINE__); //如果手机号和邮箱都没有注册、则返回参数错误
        }

        if($mobile) {
            if(!user_helper::is_mobile($mobile) || !user_helper::is_mobile_unique($mobile))
            {
                auth_helper::returnAuthData(auth_config::$auth_return_msg['mobile_err'], __LINE__);//请填写手机或者邮箱
            }

            //这一步拿验证码
            $codes =  auth_helper::getKvdata($mobile, 'register');
            //判断短信验证码
            if($smscode =='' || $codes['code']!=$smscode )
            {
                //验证码错误
                auth_helper::returnAuthData(auth_config::$auth_return_msg['smscode_err'],__LINE__);//验证码错误
            }
            //验证码过期
            if($codes['times'] + 600 < time())
            {
                auth_helper::returnAuthData(auth_config::$auth_return_msg['smscode_exp'],__LINE__);//验证码过期
            }
        }

        if($email) {
            if (!user_helper::is_email($email) || !user_helper::is_email_unique($email)) {
                auth_helper::returnAuthData(auth_config::$auth_return_msg['mail_ext'], __LINE__);//邮箱已被注册
            }
        }

        if(user_helper::is_pwd_null($password) && !user_helper::is_strlen_scope($password, 6))
        {
            //密码格式不正确
            auth_helper::returnAuthData(auth_config::$auth_return_msg['pass_err'],__LINE__);//密码格式不正确
        }

        if($nickname == '' || !user_helper::is_username_len($nickname)) {
            auth_helper::returnAuthData(auth_config::$auth_return_msg['nick_err'],__LINE__);//昵称格式不正确
        }

        if(!user_helper::is_username_unique($nickname)) {
            auth_helper::returnAuthData(auth_config::$auth_return_msg['nick_err'],__LINE__);//随机的用户名已经存在提示昵称格式不正确
        }

        $hash = user_helper::random_hash(6);
        $info = array(
                'user_name' => $nickname,
                'password' => user_helper::md5_password($password, $hash),
                'hash'     => $hash,
                'email'    => $email,
                'mobile'   => $mobile,
                'nickname' => $nickname,
                'user_from'=> 'glassapp'
        );

        // 主键冲突
        if(!$info['email']) {
            unset($info['email']);
        }
        if(!$info['mobile']) {
            unset($info['mobile']);
        }

        $user_id = _model('user')->create($info);
        if($user_id) {
            _model('role_user')->create(array('role_id' => '2', 'user_id' => $user_id));
            $return_msg = user_helper::uc_register($nickname, $password, $email, $hash, $mobile);
            if($return_msg['info'] == 'ok') {
                _model('user')->update($user_id, array('uc_id' => $return_msg['uc_id']));

                //如果是邮箱注册，注册完成后发送激活邮箱邮件
                // if(user_helper::is_email($email)) {
                //         auth_helper::set_mail_send($email, $user_id, 'register');
                // }
                auth_helper::returnAuthData(auth_config::$auth_return_msg['succ'], __LINE__);
            } else {
                _model('user')->delete(array('id'=>$user_id));
                _model('role_user')->delete(array('user_id' => $user_id));
            }
        }
        auth_helper::returnAuthData(auth_config::$auth_return_msg['unknow_err'], __LINE__);
    }


    //发短信function
    public function sendsms()
    {
        $mobile = Request::Post('mobile', '');
        if(!user_helper::is_mobile($mobile)) {
            auth_helper::returnAuthData(auth_config::$auth_return_msg['mobile_err'],__LINE__);
        }

         if(!auth_helper::checkGen($this->randid, $this->appkey, $this->appskey, $this->key)) {
             auth_helper::returnAuthData(auth_config::$auth_return_msg['check_err'],__LINE__);
         }

        if(!user_helper::is_mobile_unique($mobile)) {
            auth_helper::returnAuthData(auth_config::$auth_return_msg['mobile_ext'],__LINE__);
        }

        //发送短信
        if(sms_helper::sendRegSms($mobile, 'register')) {
            auth_helper::returnAuthData(auth_config::$auth_return_msg['succ'], __LINE__);
        }else{
            auth_helper::returnAuthData(auth_config::$auth_return_msg['sms_err'], __LINE__);
        }

    }

    //登录 返回唯一token单独存放在独立表中
    public function login()
    {
        $username = trim(Request::Post('username', ''));
        $password = trim(Request::Post('password', ''));

        //结合用户注册  判断用户名格式 手机或者是邮
        if(!auth_helper::checkGen($this->randid, $this->appkey, $this->appskey, $this->key))
        {
            auth_helper::returnAuthData(auth_config::$auth_return_msg['check_err'], __LINE__);
        }

        if(user_helper::is_email($username)) {
            $info = array(
                'email'    => $username
            );
            $user_info = _uri('user', $info);
        } elseif(user_helper::is_mobile($username)) {
            $info = array(
                    'mobile'    => $username
            );
            $user_info = _uri('user', $info);
        } else {
            auth_helper::returnAuthData(auth_config::$auth_return_msg['usr_err'], __LINE__);
        }

        if(!$user_info) {
            auth_helper::returnAuthData(auth_config::$auth_return_msg['usrpass_err'], __LINE__);
        }
        $info['password'] = user_helper::md5_password($password, $user_info['hash']);

        $user_info = _model('user')->read($info);

        $data =array();

        if(is_array($user_info))
        {
            if(!empty($user_info['id']) && $user_info['id'] > 0)
            {

                //获得个人信息  获得加密的token
                $token = $this->genToken($user_info['id']);
                $data['uid'] = $user_info['id'];
                $data['uname'] = $user_info['nickname'];
                $data['profile_image'] = _image($user_info['avatar']);
                $data['token'] = $token;
                //过期时间
                if($this->config['authtime'] > 0)
                    $data['exptime'] = time()+$this->config['authtime'];
                else
                    $data['exptime'] = 0;
                auth_helper::returnAuthData(auth_config::$auth_return_msg['succ'],__LINE__,$data);

            }else{
                auth_helper::returnAuthData(auth_config::$auth_return_msg['usrpass_err'],__LINE__,$data);
            }
            //var_dump($data);
        }else{
            auth_helper::returnAuthData(auth_config::$auth_return_msg['usrpass_err'],__LINE__,$data);
        }
    }


    //刷新token   olotoken ,key 通过skey 和uid 加密完成  更新数据库中的token
    public function refresh_token()
    {
        //$oldtoken,$uid
        $token = Request::Post('oldtoken', '');
        $uid = Request::Post('uid', '');
        if(!$this->check_token($token))//token验证失败
        {
            auth_helper::returnAuthData(auth_config::$auth_return_msg['token_err'],__LINE__);
        }
        $data = _model('auth_token')->read(array('token' => $token));
        if($data['uid'] != $uid)
        {
            auth_helper::returnAuthData(auth_config::$auth_return_msg['token_err'],__LINE__);
        }else{
            $token = $this->genToken($uid);	//重新生成token
            $data = array();
            $data['token'] = $token;
            $data['exptime'] = $this->config['authtime'] > 0 ? (time() + $this->config['authtime']) : 0;
            auth_helper::returnAuthData(auth_config::$auth_return_msg['succ'],__LINE__);
        }
    }

    public function check_token($token)
    {
        //是否过期 是否正确
        $token_info = _model('auth_token')->read(array('token' => $token));
        if($token_info['uid'] <= 0)
        {
            return false;
        }
        if($this->appkey != $token_info['appkey'] || $token!=hash('sha256',md5($token_info['uid'].$token_info['randid'].$this->appkey).$this->appskey))
        {
            //echo __LINE__;
            return false;
        }
        //判断是否过期
        if(strtotime($token_info['update_time']) + $this->config['authtime'] < time() && $this->config['authtime'] > 0)
        {
            return false;
        }else{
            return $token_info['uid'];
        }
    }

    //获得登陆用户的基本信息
    public function get_userinfo()
    {
        //验证token
        $token = Request::Post('token', '');
        $uid   = $this->check_token($token);
        if(!$uid)//token验证失败
        {
            auth_helper::returnAuthData(auth_config::$auth_return_msg['token_err'],__LINE__);
        }
        $user_info = _uri('user', $uid);
        if(is_array($user_info) && $user_info['id'] > 0)
        {
            $data = array(
                    'user_id'   => $user_info['id'],
                    'user_name' => $user_info['user_name'],
                    'email'     => $user_info['email'],
                    'sex'       => $user_info['gender'],
                    'birthday'  => $user_info['birthday'],
                    'reg_time'  => strtotime($user_info['add_time']),
                    'profile_image' => user_helper::avatar($user_info['id']),
                    'nickname'  => $user_info['nickname'],
                    'mobile_phone' => $user_info['mobile'],
                    'realname'  => $user_info['realname']
            );
            auth_helper::returnAuthData(auth_config::$auth_return_msg['succ'],__LINE__,$data);
        }else{
            auth_helper::returnAuthData(auth_config::$auth_return_msg['token_err'],__LINE__);
        }
        //获得基本信息
    }


    //生成token
    public function genToken($uid)
    {
        //时间+随机+appskye +appkey

        $randid = time().rand(10000,99999);
        $token = hash('sha256',md5($uid.$this->randid.$this->appkey).$this->appskey);
        $ip = Request::getClientIp();
        $token_info = _uri('auth_token', $uid);
        $info = array(
                'token'  => $token,
                'randid' => $this->randid,
                'add_ip' => $ip,
                'appkey' => $this->appkey
        );
        if($token_info) {
            _model('auth_token')->update($uid, $info);
        } else {
            $info['uid'] = $uid;
            _model('auth_token')->create($info);
        }
        return $token;
    }


    //修改密码
    public function mod_password()
    {
        $token = Request::Post('token', '');
        $oldpass = Request::Post('oldpass', '');//老密码
        $newpass = Request::Post('newpass', '');//新密码
        //checktoken
        $uid = $this->check_token($token);
        if(!$uid)//token验证失败
        {
            auth_helper::returnAuthData(auth_config::$auth_return_msg['token_err'],__LINE__);
        }
        //验证传输方式
        if(!auth_helper::checkGen($this->randid, $this->appkey, $this->appskey, $this->key))
        {
            auth_helper::returnAuthData(auth_config::$auth_return_msg['check_err'],__LINE__);
        }
        if($oldpass == $newpass)//密码一致不能修改
        {
            auth_helper::returnAuthData(auth_config::$auth_return_msg['oldpass_err'],__LINE__);
        }

        if(user_helper::is_pwd_null($newpass) && !user_helper::is_strlen_scope($newpass, 6))
        {
            auth_helper::returnAuthData(auth_config::$auth_return_msg['pass_err'],__LINE__);//密码格式不正确
        }

        $user_info = _uri('user', $uid);
        $check_old_pw = user_helper::md5_password($oldpass, $user_info['hash']);
        if($check_old_pw != '' && $check_old_pw == $user_info['password']) {
            //修改nbd官网的密码
            _model('user')->update($uid, array('password' => user_helper::md5_password($newpass, $user_info['hash'])));
            //修改uc的密码
            user_helper::uc_edit($user_info['uc_id'], $user_info['user_name'], $user_info['email'], $newpass);
            auth_helper::returnAuthData(auth_config::$auth_return_msg['succ'],__LINE__);
        } else {
            auth_helper::returnAuthData(auth_config::$auth_return_msg['oldpass_err'],__LINE__);//密码错误
        }
    }

    public function moduserinfo()
    {
        $userinfo['nickname'] = Request::Post('nickname', '');//昵称
        $userinfo['realname'] = Request::Post('realname', '');//真实姓名
        $userinfo['gender'] = intval(Request::Post('sex'));//性别
        $userinfo['birthday'] = Request::Post('birthday', '');//出生日期

        $token = Request::Post('token', '');
        //验证token
        $uid = $this->check_token($token);
        if(!$uid)//token验证失败
        {
            auth_helper::returnAuthData(auth_config::$auth_return_msg['token_err'],__LINE__);
        }
        //验证传输方式
        if(!auth_helper::checkGen($this->randid, $this->appkey, $this->appskey, $this->key))
        {
            auth_helper::returnAuthData(auth_config::$auth_return_msg['check_err'],__LINE__);
        }
        //验证真实姓名是否为空
        // if($userinfo['realname'] == '')
        // {
        //     auth_helper::returnAuthData(auth_config::$auth_return_msg['realname_err'],__LINE__);
        // }
        //验证性别是否为空

        // if(empty($userinfo['nickname']) && !user_helper::is_username_unique($userinfo['nickname'])) {
        //     auth_helper::returnAuthData(auth_config::$auth_return_msg['nick_err'],__LINE__);//随机的用户名已经存在提示昵称格式不正确
        // }

        if($userinfo['gender'] < 0 || $userinfo['gender'] > 2 )
        {
            auth_helper::returnAuthData(auth_config::$auth_return_msg['unknow_err'],__LINE__);
        }

        //如果不传生日，则不更新生日
        if(!empty($userinfo['birthday'])) {
            //验证生日1954-01-01  checkdate(2, 29, 2001)
            $datas = explode("-",$userinfo['birthday']);

            if(!checkdate($datas[1], $datas[2], $datas[0]))
            {
                auth_helper::returnAuthData(auth_config::$auth_return_msg['birth_err'],__LINE__);
            }
        } else {
            unset($userinfo['birth_err']);
        }
        // $user_info = _uri('user', $uid);


        $affected = _model('user')->update($uid, $userinfo);

        //保存到数据库中
        if(!$affected) {
            auth_helper::returnAuthData(auth_config::$auth_return_msg['usr_ext'],__LINE__);
        } else {
            auth_helper::returnAuthData(auth_config::$auth_return_msg['succ'],__LINE__);
        }


    }

    /**
     * 置换nbdid
     */
    public function exchangenbdid()
    {
        $uc_id    = Request::Post('old_uid', 0);
        $nickname = Request::Post('nickname', '');
        $email    = Request::Post('email', '');
        $mobile   = Request::Post('mobile', '');

        //结合用户注册  判断用户名格式 手机或者是邮
        if(!auth_helper::checkGen($this->randid, $this->appkey, $this->appskey, $this->key))
        {
            auth_helper::returnAuthData(auth_config::$auth_return_msg['check_err'], __LINE__);
        }

        if(!$uc_id && !$nickname && !$email && !$mobile) {
            auth_helper::returnAuthData(auth_config::$auth_return_msg['parm_err'], __LINE__);
        }

        $filter = array();
        if($uc_id) {
            $filter['uc_id'] = $uc_id;
        }
        if($nickname) {
            $filter['username'] = $nickname;
        }
        if($email) {
            $filter['email'] = $email;
        }
        if($mobile) {
            $filter['mobile'] = $mobile;
        }
        $user_info = _uri('user', $filter);

        if($user_info) {
            auth_helper::returnAuthData(auth_config::$auth_return_msg['succ'],__LINE__, array(
                'uid' => $user_info['id']
            ));
        } else {
            auth_helper::returnAuthData(auth_config::$auth_return_msg['succ'],__LINE__, array(
                'uid' => 0
            ));
        }

    }


    /*
    * 上传图片（蒙奇笔）
    */
   // public function upload_pic()
   // {
   //      $token = Request::Post('token', '');
   //      $title = Request::Post('title', '');
   //      $desc  = Request::Post('desc', '');
   //      $base64_pic = Request::Post('pic', '');
   //      if(!$base64 _pic) {
   //          auth_helper::returnAuthData(auth_config::$auth_return_msg['parm_err'], __LINE__);
   //      }
   //      $uid = $this->check_token($token);
   //      if(!$uid)//token验证失败
   //      {
   //          auth_helper::returnAuthData(auth_config::$auth_return_msg['token_err'],__LINE__);
   //      }





   // }

}